package com.caiheng.api.service.product.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.caiheng.api.dao.mer.MerMapper;
import com.caiheng.api.dao.platform.PlatformSplitMapper;
import com.caiheng.api.entity.dto.*;
import com.caiheng.api.entity.mer.Mer;
import com.caiheng.api.entity.platform.Parameter;
import com.caiheng.api.entity.product.*;
import com.caiheng.api.exception.TransactionalException;
import com.caiheng.api.service.base.impl.BaseServiceImpl;
import com.caiheng.api.service.platfom.ParameterService;
import com.caiheng.api.service.product.ProductAttrService;
import com.caiheng.api.service.product.ProductAttrValueService;
import com.caiheng.api.service.product.ProductOrderInfoService;
import com.caiheng.api.service.product.ProductService;
import com.caiheng.api.util.DateUtil;
import com.caiheng.api.util.RegexUtil;
import com.caiheng.api.dao.product.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ProductServiceImpl extends BaseServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductAttrMapper productAttrMapper;
    @Resource
    private ProductRuleMapper productRuleMapper;
    @Resource
    private ProductAttrValueMapper productAttrValueMapper;
    @Resource
    private ProductEstateMapper productEstateMapper;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private ProductAttrService productAttrService;
    @Autowired
    private ProductOrderInfoService productOrderInfoService;
    @Resource
    private PlatformSplitMapper platformSplitMapper;
    @Resource
    private MerMapper merMapper;
    @Resource
    private ParameterService parameterService;
    @Resource
    private ProductImgMapper productImgMapper;
    @Resource
    private ProductCartMapper productCartMapper;

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片地址

    @Override
    @Transactional
    public long addProduct(Product product,int save_index,int merId) {
        try{
            //商品描述
            if(save_index == 3){
                product.setDescription(RegexUtil.converProductDescription(product.getDescription()));
            }
            product.setCateId(2);
            product.setIsUseIntegral(0);
            if(product.getId() == 0){
                product.setCreateTime(new Date());
            }

            if(product.getIsActive() == 1 && product.getActiveDateRange()!=null){
                String[] dateRange = product.getActiveDateRange();
                Date freeBeginTime = DateUtil.ConvertDateByformat( dateRange[0] + " 00:00:00","yyyy-MM-dd HH:mm:ss");
                Date freeEndTime = DateUtil.ConvertDateByformat( dateRange[1] + " 23:59:59","yyyy-MM-dd HH:mm:ss");
                product.setActiveBeginTime(freeBeginTime);
                product.setActiveEndTime(freeEndTime);
            }

            //商品规格
            if(save_index == 1){
                if(product.getIsSale() == 1){
                    ProductResultDto resultDTO = this.computedProduct(product.getAttrs());
                    product.setPrice(BigDecimal.valueOf(resultDTO.getMinPrice()));
                    product.setOtPrice(BigDecimal.valueOf(resultDTO.getMinOtPrice()));
                    product.setStock(resultDTO.getStock());
                }
            }
            product.setMerId(merId);
            boolean bl = this.saveOrUpdate(product);
            if(bl){
                String sliderImg = "";
                QueryWrapper<ProductImg> qw = new QueryWrapper<>();
                qw.eq("product_id",product.getId());
                qw.eq("img_type", 1);
                List<ProductImg> sliderImgs = productImgMapper.selectList(qw);
                if(CollUtil.isNotEmpty(sliderImgs)){
                    for (ProductImg img : sliderImgs){
                        sliderImg += img.getImgUrl() + ",";
                    }
                }
                if(StrUtil.isNotEmpty(sliderImg)){
                    sliderImg = sliderImg.substring(0,sliderImg.length() - 1);
                    product.setSliderImage(sliderImg);
                    productMapper.updateById(product);
                }
            }

            if(save_index == 1 && product.getIsSale() == 1) {
                //属性处理
                //处理单sKu
                if (product.getSpecType() == 0) {// 单规格
                    FromatDetailDto fromatDetailDto = FromatDetailDto.builder()
                            .value("规格").detailValue("")
                            .attrHidden("")
                            .detail(ListUtil.toList("默认"))
                            .build();
                    List<ProductFormatDto> attrs = product.getAttrs();
                    ProductFormatDto productFormatDto = attrs.get(0);
                    productFormatDto.setValue1("规格");
                    Map<String, String> map = new HashMap<>();
                    map.put("规格", "默认");
                    productFormatDto.setDetail(map);
                    productAttrService.insertProductAttr(ListUtil.toList(fromatDetailDto), ListUtil.toList(productFormatDto), product.getId());
                } else {
                    //多规格
                    productAttrService.insertProductAttr(product.getItems(), product.getAttrs(), product.getId());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw  new TransactionalException("");
        }
        return product.getId();
    }

    /**
     * 获取生成的属性
     *
     * @param id      商品id
     * @param jsonStr jsonStr
     * @return map
     */
    @Override
    public Map<String, Object> getFormatAttr(Long id, String jsonStr, boolean isActivity, Integer isReset) {
        JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
        if(jsonArray.size() > 0){
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            Map<String, Object> resultMap = new LinkedHashMap<>(3);
            if (jsonObject == null || jsonObject.get("detail") == null || jsonObject.getJSONArray("detail").isEmpty()) {
                resultMap.put("attr", new ArrayList<>());
                resultMap.put("value", new ArrayList<>());
                resultMap.put("header", new ArrayList<>());
                return resultMap;
            }
            try{
                List<FromatDetailDto> fromatDetailDTOList = JSONUtil.toList(jsonStr,FromatDetailDto.class);
                DetailDto detailDto = this.attrFormat(fromatDetailDTOList);
                List<Map<String, Object>> headerMapList = null;
                List<Map<String, Object>> valueMapList = new ArrayList<>();
                String align = "center";
                Map<String, Object> headerMap = new LinkedHashMap<>();
                for (Map<String, Map<String, String>> map : detailDto.getRes()) {
                    Map<String, String> detail = map.get("detail");
                    String[] detailArr = detail.values().toArray(new String[]{});
                    Arrays.sort(detailArr);
                    String sku = String.join(",", detailArr);
                    Map<String, Object> valueMap = new LinkedHashMap<>();
                    List<String> detailKeys = detail.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toList());
                    int i = 0;
                    headerMapList = new ArrayList<>();
                    for (String title : detailKeys) {
                        headerMap.put("title", title);
                        headerMap.put("minWidth", "120");
                        headerMap.put("align", align);
                        headerMap.put("key", "value" + (i + 1));
                        headerMap.put("slot", "value" + (i + 1));
                        headerMapList.add(ObjectUtil.clone(headerMap));
                        i++;
                    }

                    String[] detailValues = detail.values().toArray(new String[]{});
                    for (int j = 0; j < detailValues.length; j++) {
                        String key = "value" + (j + 1);
                        valueMap.put(key, detailValues[j]);
                    }

                    valueMap.put("id", 0);
                    valueMap.put("detail", detail);
                    valueMap.put("price", 0);
                    valueMap.put("otPrice", 0);
                    valueMap.put("stock", 0);
                    if (id > 0) {
                        ProductAttrValue productAttrValue = productAttrValueService
                                .getOne(Wrappers.<ProductAttrValue>lambdaQuery()
                                        .eq(ProductAttrValue::getProductId, id)
                                        .eq(ProductAttrValue::getSku, sku)
                                        .last("limit 1"));
                        if (productAttrValue != null) {
                            valueMap.put("id", productAttrValue.getId());
                            valueMap.put("price", productAttrValue.getPrice());
                            valueMap.put("cost", productAttrValue.getCost());
                            valueMap.put("otPrice", productAttrValue.getOtPrice());
                            valueMap.put("stock", productAttrValue.getStock());

                            valueMapList.add(ObjectUtil.clone(valueMap));
                        }else{
//                            if(isReset == 1){
//                                valueMapList.add(ObjectUtil.clone(valueMap));
//                            }
                            valueMapList.add(ObjectUtil.clone(valueMap));
                        }
                    }else{
                        valueMapList.add(ObjectUtil.clone(valueMap));
                    }
                }

                this.addMap(headerMap, headerMapList, align);

                resultMap.put("attr", fromatDetailDTOList);
                resultMap.put("value", valueMapList);
                resultMap.put("header", headerMapList);

            }catch (Exception e){
                e.printStackTrace();
            }
            return resultMap;
        }
        return null;
    }

    /**
     * 增加表头
     *
     * @param headerMap     headerMap
     * @param headerMapList headerMapList
     * @param align         align
     */
    private void addMap(Map<String, Object> headerMap, List<Map<String, Object>> headerMapList, String align) {

        headerMap.put("title", "售价");
        headerMap.put("slot", "price");
        headerMap.put("align", align);
        headerMap.put("minWidth", 120);
        headerMapList.add(ObjectUtil.clone(headerMap));

        headerMap.put("title", "原价");
        headerMap.put("slot", "otPrice");
        headerMap.put("align", align);
        headerMap.put("minWidth", 120);
        headerMapList.add(ObjectUtil.clone(headerMap));

        headerMap.put("title", "库存");
        headerMap.put("slot", "stock");
        headerMap.put("align", align);
        headerMap.put("minWidth", 120);
        headerMapList.add(ObjectUtil.clone(headerMap));

        headerMap.put("title", "操作");
        headerMap.put("slot", "action");
        headerMap.put("align", align);
        headerMap.put("minWidth", 70);
        headerMapList.add(ObjectUtil.clone(headerMap));
    }

    /**
     * 组合规则属性算法
     *
     * @param fromatDetailDTOList
     * @return DetailDto
     */
    private DetailDto attrFormat(List<FromatDetailDto> fromatDetailDTOList) {

        List<String> data = new ArrayList<>();
        List<Map<String, Map<String, String>>> res = new ArrayList<>();

        fromatDetailDTOList.stream()
                .map(FromatDetailDto::getDetail)
                .forEach(i -> {
                    if (i == null || i.isEmpty()) {
//                        throw new YshopException("请至少添加一个规格值哦");
                    }
                    String str = ArrayUtil.join(i.toArray(), ",");
                    if (str.contains("-")) {
//                        throw new YshopException("规格值里包含'-',请重新添加");
                    }
                });

        if (fromatDetailDTOList.size() > 1) {
            for (int i = 0; i < fromatDetailDTOList.size() - 1; i++) {
                if (i == 0) {
                    data = fromatDetailDTOList.get(i).getDetail();
                }
                List<String> tmp = new LinkedList<>();
                for (String v : data) {
                    for (String g : fromatDetailDTOList.get(i + 1).getDetail()) {
                        String rep2 = "";
                        if (i == 0) {
                            rep2 = fromatDetailDTOList.get(i).getValue() + "_" + v + "-"
                                    + fromatDetailDTOList.get(i + 1).getValue() + "_" + g;
                        } else {
                            rep2 = v + "-"
                                    + fromatDetailDTOList.get(i + 1).getValue() + "_" + g;
                        }

                        tmp.add(rep2);

                        if (i == fromatDetailDTOList.size() - 2) {
                            Map<String, Map<String, String>> rep4 = new LinkedHashMap<>();
                            Map<String, String> reptemp = new LinkedHashMap<>();
                            for (String h : Arrays.asList(rep2.split("-"))) {
                                List<String> rep3 = Arrays.asList(h.split("_"));
                                if (rep3.size() > 1) {
                                    reptemp.put(rep3.get(0), rep3.get(1));
                                } else {
                                    reptemp.put(rep3.get(0), "");
                                }
                            }
                            rep4.put("detail", reptemp);

                            res.add(rep4);
                        }
                    }

                }

                if (!tmp.isEmpty()) {
                    data = tmp;
                }
            }
        } else {
            List<String> dataArr = new ArrayList<>();
            for (FromatDetailDto fromatDetailDTO : fromatDetailDTOList) {
                for (String str : fromatDetailDTO.getDetail()) {
                    Map<String, Map<String, String>> map2 = new LinkedHashMap<>();
                    dataArr.add(fromatDetailDTO.getValue() + "_" + str);
                    Map<String, String> map1 = new LinkedHashMap<>();
                    map1.put(fromatDetailDTO.getValue(), str);
                    map2.put("detail", map1);
                    res.add(map2);
                }
            }
            String s = StrUtil.join("-", dataArr);
            data.add(s);
        }

        DetailDto detailDto = new DetailDto();
        detailDto.setData(data);
        detailDto.setRes(res);

        return detailDto;
    }

    /**
     * 计算产品数据
     *
     * @param attrs attrs
     * @return ProductResultDto
     */
    private ProductResultDto computedProduct(List<ProductFormatDto> attrs) {
        //取最小价格
        Double minPrice = attrs
                .stream()
                .map(ProductFormatDto::getPrice)
                .min(Comparator.naturalOrder())
                .orElse(0d);

        Double minOtPrice = attrs
                .stream()
                .map(ProductFormatDto::getOtPrice)
                .min(Comparator.naturalOrder())
                .orElse(0d);

//        Double minCost = attrs
//                .stream()
//                .map(ProductFormatDto::getCost)
//                .min(Comparator.naturalOrder())
//                .orElse(0d);
        //计算库存
        Integer stock = attrs
                .stream()
                .map(ProductFormatDto::getStock)
                .reduce(Integer::sum)
                .orElse(0);

        return ProductResultDto.builder()
                .minPrice(minPrice)
                .minOtPrice(minOtPrice)
                .stock(stock)
                .build();
    }

    @Override
    public Product getProductInfoById(Integer id,Integer isSimple) {
        Product product = productMapper.selectById(id);
        if(product != null){
            if(product.getImage().indexOf("https") < 0){
                product.setImage(imgPrefix + product.getImage());
            }
            if(isSimple == 0) {
                if (StrUtil.isNotEmpty(product.getImage())) {
                    List<ProductImgDto> productImgDtos = new ArrayList<>();
                    QueryWrapper<ProductImg> qwImgs = new QueryWrapper<>();
                    qwImgs.eq("product_id", product.getId());
                    qwImgs.eq("img_type", 0);
                    List<ProductImg> productImg = productImgMapper.selectList(qwImgs);
                    if (CollUtil.isNotEmpty(productImg)) {
                        for (ProductImg img : productImg) {

                            ProductImgDto imgDto = new ProductImgDto();
                            imgDto.setId(img.getId());
                            imgDto.setUrl(imgPrefix + img.getImgUrl());
                            imgDto.setName("图片1");
                            productImgDtos.add(imgDto);
                        }
                    }
                    product.setProductImgs(productImgDtos);
                }


                List<String> sliderImageArray = new ArrayList<>();
                String sliderImgs = "";
                product.setSliderImageArray(sliderImageArray);
                if (StrUtil.isNotEmpty(product.getSliderImage())) {
                    String[] sliderImages = product.getSliderImage().split(",");
                    for (String img : sliderImages) {
                        if (img.indexOf("https") < 0) {
                            sliderImageArray.add(imgPrefix + img);
                            sliderImgs += imgPrefix + img + ",";
                        } else {
                            sliderImageArray.add(img);
                            sliderImgs += img + ",";
                        }
                    }
                    if (sliderImgs.length() > 0) {
                        sliderImgs = sliderImgs.substring(0, sliderImgs.length() - 1);
                    }
                    product.setSliderImage(sliderImgs);
                    product.setSliderImageArray(sliderImageArray);
                }


                List<ProductImgDto> productSlideImgDtos = new ArrayList<>();
                QueryWrapper<ProductImg> qwSlideImgs = new QueryWrapper<>();
                qwSlideImgs.eq("product_id", product.getId());
                qwSlideImgs.eq("img_type", 1);
                List<ProductImg> sliderImages = productImgMapper.selectList(qwSlideImgs);
                if (CollUtil.isNotEmpty(sliderImages)) {
                    for (ProductImg img : sliderImages) {
//                    img.setImgUrl(imgPrefix + img.getImgUrl());
                        ProductImgDto imgDto = new ProductImgDto();
                        imgDto.setId(img.getId());
                        imgDto.setUrl(imgPrefix + img.getImgUrl());
                        imgDto.setName("图片1");
                        productSlideImgDtos.add(imgDto);
                    }
                }
                product.setSliderImgs(productSlideImgDtos);


                if (product.getIsActive() != null && product.getIsActive() == 1) {
                    String activeTime = "";
                    activeTime = DateUtil.getMonthDay(product.getActiveBeginTime()) + " ~ " + DateUtil.getMonthDay(product.getActiveEndTime());
                    product.setActiveTime(activeTime);
                }


                ProductRule rule = productRuleMapper.selectOne(new LambdaQueryWrapper<ProductRule>().eq(ProductRule::getId, product.getRuleId()));
                if (rule != null) {
                    if (StrUtil.isNotEmpty(rule.getRuleValue())) {
                        rule.setRuleValueArray(JSONUtil.parseArray(rule.getRuleValue()));
                    }
                }
                product.setRule(rule);
                Mer mer = null;
                if (product.getMerId() != null) {
                    mer = merMapper.selectById(product.getMerId());
                    product.setMer(mer);
                }

                //获取商品sku
                Map<String, Object> returnMap = productAttrService.getProductAttrDetail(id, mer);

                //设置商品相关信息
                product.setProductAttr((List<ProductAttr>) returnMap.get("productAttr"));
                product.setProductValue((Map<String, ProductAttrValue>) returnMap.get("productValue"));
            }


            int totalCount = 0;
            QueryWrapper<ProductAttrValue> qwAttrValue = new QueryWrapper<>();
            qwAttrValue.select("id,sku,price,ot_price,stock,is_del,image");
            qwAttrValue.eq("product_id", product.getId());
            qwAttrValue.eq("is_del", 0);
            List<ProductAttrValue> productAttrValues = productAttrValueMapper.selectList(qwAttrValue);
            List<ProductFormatDto> attrs = new ArrayList<>();
            if(CollUtil.isNotEmpty(productAttrValues)){
                for (ProductAttrValue value : productAttrValues){
                    if(isSimple == 0){
                        totalCount += value.getStock();
                        if(StrUtil.isNotEmpty(value.getImage())){
                            if(value.getImage().indexOf("https") < 0){
                                value.setImage(imgPrefix + value.getImage());
                            }else{
                                value.setImage(value.getImage());
                            }
                        }else{
                            value.setImage("");
                        }
                    }

                    ProductFormatDto attr = new ProductFormatDto();
                    attr.setName(value.getSku());
                    attr.setId(value.getId());
                    attr.setPrice(value.getPrice().doubleValue());
                    attr.setOtPrice(value.getOtPrice().doubleValue());
                    attr.setStock(value.getStock());
                    attrs.add(attr);
                }
                product.setAttrs(attrs);
                product.setTotalCount(totalCount);
            }
        }
        return product;
    }

    public Product getProductInfo(Product product, int isSimple) {
        if(StrUtil.isNotEmpty(product.getImage())) {
            if (product.getImage().indexOf("https") < 0) {
                product.setImage(imgPrefix + product.getImage());
            }
        }
        if(isSimple == 0){
            if(StrUtil.isNotEmpty(product.getImage())){
                List<ProductImgDto> productImgDtos = new ArrayList<>();
                QueryWrapper<ProductImg> qwImgs = new QueryWrapper<>();
                qwImgs.eq("product_id",product.getId());
                qwImgs.eq("img_type", 0);
                List<ProductImg> productImg = productImgMapper.selectList(qwImgs);
                if(CollUtil.isNotEmpty(productImg)){
                    for (ProductImg img : productImg){

                        ProductImgDto imgDto = new ProductImgDto();
                        imgDto.setId(img.getId());
                        imgDto.setUrl(imgPrefix + img.getImgUrl());
                        imgDto.setName("图片1");
                        productImgDtos.add(imgDto);
                    }
                }
                product.setProductImgs(productImgDtos);
            }

            List<String> sliderImageArray = new ArrayList<>();
            String sliderImgs = "";
            product.setSliderImageArray(sliderImageArray);
            if(StrUtil.isNotEmpty(product.getSliderImage())){
                String[] sliderImages = product.getSliderImage().split(",");
                for (String img: sliderImages){
                    if(img.indexOf("https") < 0){
                        sliderImageArray.add(imgPrefix + img);
                        sliderImgs += imgPrefix + img + ",";
                    }else{
                        sliderImageArray.add(img);
                        sliderImgs += img + ",";
                    }
                }
                if(sliderImgs.length() > 0){
                    sliderImgs = sliderImgs.substring(0,sliderImgs.length() - 1);
                }
                product.setSliderImage(sliderImgs);
                product.setSliderImageArray(sliderImageArray);
            }

            List<ProductImgDto> productSlideImgDtos = new ArrayList<>();
            QueryWrapper<ProductImg> qwSlideImgs = new QueryWrapper<>();
            qwSlideImgs.eq("product_id",product.getId());
            qwSlideImgs.eq("img_type", 1);
            List<ProductImg> sliderImages = productImgMapper.selectList(qwSlideImgs);
            if(CollUtil.isNotEmpty(sliderImages)){
                for (ProductImg img : sliderImages){
                    ProductImgDto imgDto = new ProductImgDto();
                    imgDto.setId(img.getId());
                    imgDto.setUrl(imgPrefix + img.getImgUrl());
                    imgDto.setName("图片1");
                    productSlideImgDtos.add(imgDto);
                }
            }
            product.setSliderImgs(productSlideImgDtos);

            if(product.getIsActive()!=null && product.getIsActive() == 1){
                String activeTime = "";
                activeTime = DateUtil.getMonthDay(product.getActiveBeginTime()) + " ~ " + DateUtil.getMonthDay(product.getActiveEndTime());
                product.setActiveTime(activeTime);
            }

            ProductRule rule = productRuleMapper.selectOne(new LambdaQueryWrapper<ProductRule>().eq(ProductRule::getId, product.getRuleId()));
            if(rule!=null){
                if(StrUtil.isNotEmpty(rule.getRuleValue())){
                    rule.setRuleValueArray(JSONUtil.parseArray(rule.getRuleValue()));
                }
            }
            product.setRule(rule);

            Mer mer = null;
            if(product.getMerId()!=null){
                mer = merMapper.selectById(product.getMerId());
                product.setMer(mer);
            }

            //获取商品sku
            Map<String, Object> returnMap = productAttrService.getProductAttrDetail(product.getId(),mer);

            //设置商品相关信息
            product.setProductAttr((List<ProductAttr>) returnMap.get("productAttr"));
            product.setProductValue((Map<String, ProductAttrValue>) returnMap.get("productValue"));
        }

        int totalCount = 0;
        QueryWrapper<ProductAttrValue> qwAttrValue = new QueryWrapper<>();
        qwAttrValue.select("id,sku,price,ot_price,stock,is_del,image");
        qwAttrValue.eq("product_id", product.getId());
        qwAttrValue.eq("is_del", 0);
        List<ProductAttrValue> productAttrValues = productAttrValueMapper.selectList(qwAttrValue);
        List<ProductFormatDto> attrs = new ArrayList<>();
        if(CollUtil.isNotEmpty(productAttrValues)){
            for (ProductAttrValue value : productAttrValues){
                if(isSimple == 0){
                    totalCount += value.getStock();
                    if(StrUtil.isNotEmpty(value.getImage())){
                        if(value.getImage().indexOf("https") < 0){
                            value.setImage(imgPrefix + value.getImage());
                        }else{
                            value.setImage(value.getImage());
                        }
                    }else{
                        value.setImage("");
                    }
                }

                ProductFormatDto attr = new ProductFormatDto();
                attr.setName(value.getSku());
                attr.setId(value.getId());
                attr.setPrice(value.getPrice().doubleValue());
                attr.setOtPrice(value.getOtPrice().doubleValue());
                attr.setStock(value.getStock());
                attrs.add(attr);
            }
            product.setAttrs(attrs);
            product.setTotalCount(totalCount);
        }
        return product;
    }

    @Override
    public Product getProductByOrderId(Long orderId) {
        Product product = null;
        ProductOrderInfo orderInfo = productOrderInfoService.selectOneByOrderId(orderId);
        if(orderInfo!=null){
            product = productMapper.selectById(orderInfo.getProductId());
        }
        return product;
    }

    @Override
    public List<Product> queryProductList(String productName,int productTypeId, int mer_id,int state, int is_mer,String platform,int pageIndex, int pageSize) {

        List<Product> productsNew = new ArrayList<>();
        try{

            QueryWrapper<Product> qw = new QueryWrapper<>();
            qw.eq("is_show",1);
            if(is_mer == 0){
                qw.eq("is_show",1);
            }
            qw.eq("is_del",0);
            if(mer_id > 0){
                qw.eq("mer_id",mer_id);
            }
            if(productTypeId > 0){
                qw.eq("cate_id",productTypeId);
            }
            if(StrUtil.isNotEmpty(productName)){
                qw.like("store_name",productName);
            }
            qw.orderByDesc("id");
            List<Product> list = productMapper.getPageEntityList(qw,pageIndex,pageSize);
            if (list != null && list.size() > 0){
                for (Product product : list){
                    product = getProductInfoById(product.getId(), 0);
                    productsNew.add(product);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return productsNew;
    }

    @Override
    public List<Product> queryMerProductList(String productName,int productTypeId, int mer_id, int order_id,int pageIndex, int pageSize,int isSimple) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("is_show",1);
        qw.eq("is_del",0);
        if(mer_id > 0){
            qw.eq("mer_id",mer_id);
        }
        if(productTypeId > 0){
            qw.eq("cate_id",productTypeId);
        }
        if(StrUtil.isNotEmpty(productName)){
            qw.like("store_name",productName);
        }
        qw.orderByAsc("sort");
        List<Product> productsNew = new ArrayList<>();
        List<Product> list = productMapper.getPageEntityList(qw,pageIndex,pageSize);
        if (list != null && list.size() > 0){
            for (Product product : list){
                product = getProductInfo(product,isSimple);

                QueryWrapper<ProductCart> qwCart = new QueryWrapper<>();
                if(order_id > 0){
                    qwCart.eq("order_id", order_id);
                }
                qwCart.eq("product_id",product.getId());
                qwCart.eq("mer_id",mer_id);
                qwCart.eq("is_pay", 0);
                qwCart.eq("is_del", 0);
                qwCart.last("limit 1");
                ProductCart cart = productCartMapper.selectOne(qwCart);
                if(cart != null){
                    product.setProductCart(cart);
                }
                productsNew.add(product);
            }
        }
        return productsNew;
    }

    @Override
    public List<Product> queryEstateServiceList(String productName,int merId, int estateId, int productTypeId,int pageIndex, int pageSize) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("is_show",1);
        qw.eq("is_del",0);
        qw.eq("mer_id",merId);
        if(productTypeId > 0){
            qw.eq("cate_id",productTypeId);
        }
        if(StrUtil.isNotEmpty(productName)){
            qw.like("store_name",productName);
        }
        qw.orderByAsc("sort");
        List<Product> productsNew = new ArrayList<>();
        List<Product> list = productMapper.getPageEntityList(qw,pageIndex,pageSize);
        if (CollUtil.isNotEmpty(list)){
            for (Product product : list){
                product = getProductInfo(product, 0);
                productsNew.add(product);
            }
        }
        return productsNew;
    }


    @Override
    public List<Product> queryPointProductList(String productName, int estateId, int productTypeId,int pageIndex, int pageSize) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("is_show",1);
        qw.eq("is_del",0);
        qw.eq("estate_id",estateId);
        qw.eq("is_can_use_golden", 1);
        if(productTypeId > 0){
            qw.eq("cate_id",productTypeId);
        }
        if(StrUtil.isNotEmpty(productName)){
            qw.like("store_name",productName);
        }
        qw.orderByAsc("sort");
        List<Product> productsNew = new ArrayList<>();
        List<Product> list = productMapper.getPageEntityList(qw,pageIndex,pageSize);
        if (CollUtil.isNotEmpty(list)){
            for (Product product : list){
                product = getProductInfo(product, 0);
                productsNew.add(product);
            }
        }
        return productsNew;
    }


    @Override
    public List<Product> queryProductList(String productName,Integer isHot, int cateId, String platform,int pageIndex, int pageSize) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("is_show",1);
        qw.eq("is_del",0);
        if(isHot != null){
            qw.eq("is_hot",isHot);
        }
        if(StrUtil.isNotEmpty(productName)){
            qw.like("store_name",productName);
        }
        if(cateId > 0){
            qw.eq("cate_id",cateId);
        }
        qw.orderByAsc("sort");
        List<Product> productsNew = new ArrayList<>();
        List<Product> list = productMapper.getPageEntityList(qw, pageIndex, pageSize);
        if (list != null && list.size() > 0){
            for (Product product : list){
                product = getProductInfoById(product.getId(), 0);
                productsNew.add(product);
            }
        }
        return productsNew;
    }

    @Override
    public List<Product> queryProductListPlatform(String productName,Integer isHot, int cateId, String platform,int pageIndex, int pageSize) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("is_show",1);
        qw.eq("is_del",0);
//        if(isHot != null){
//            qw.eq("is_hot",isHot);
//        }
        if(StrUtil.isNotEmpty(productName)){
            qw.like("store_name",productName);
        }
        if(cateId > 0){
            qw.eq("cate_id",cateId);
        }
        qw.orderByAsc("sort");
        List<Product> productsNew = new ArrayList<>();
        List<Product> list = productMapper.getPageEntityList(qw, pageIndex, pageSize);
        if (CollUtil.isNotEmpty(list)){
            for (Product product : list){
                product = getProductInfoById(product.getId(), 0);
                productsNew.add(product);
            }
        }
        return productsNew;
    }

    @Override
    public List<Product> queryProductList(Integer seller_id,int limit) {
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("mer_id",seller_id);
        qw.eq("is_show",1);
        qw.eq("is_del",0);
        if(limit > 0){
            qw.last("limit " + limit);
        }
        qw.orderByAsc("sort");
        List<Product> products = productMapper.selectList(qw);
        List<Product> productsNew = new ArrayList<>();
        for (Product product : products){
            product = getProductInfo(product, 0);
            productsNew.add(product);
        }
        return productsNew;
    }

    @Override
    public void resetImg() {
        List<Product> products = productMapper.selectAllList();
        for (Product product : products){

            String[] imgs = product.getImage().split(",");
            int index = 0;
            for (String img : imgs){
                if(StrUtil.isNotEmpty(img)) {
                    ProductImg productImg = new ProductImg();
                    productImg.setProductId(product.getId());
                    productImg.setImgType(0);
                    productImg.setImgUrl(img);
                    productImg.setSort(index);
                    index++;
                    productImgMapper.insert(productImg);
                }
            }

            String[] imgsLunbo = product.getSliderImage().split(",");
            int indexLunbo = 0;
            for (String img : imgsLunbo){
                if(StrUtil.isNotEmpty(img)){
                    ProductImg productImg = new ProductImg();
                    productImg.setProductId(product.getId());
                    productImg.setImgType(1);
                    productImg.setImgUrl(img);
                    productImg.setSort(indexLunbo);
                    indexLunbo++;
                    productImgMapper.insert(productImg);
                }
            }
        }
    }

}
